import storage from '@/utils/storage.js';
import config from "@/utils/config.js";
import permission from "@/utils/permission.js";

let router_arr = []
let code_arr = [50100, 501001, 401, 40100, 40200, 40220]

let obj = {
	config, // 地址配置
	storage, // token
	permission, // 权限验证
	// 参数 CAMERA 摄像头，READ_EXTERNAL_STORAGE 相册读取权限，WRITE_EXTERNAL_STORAGE 相册写入权限 RECORD_AUDIO 麦克风权限
	openidMiniApp: "",
	unionId: "",
	video_details: "",
	customerService() {
		plus.runtime.openURL(
			"https://work.weixin.qq.com/kfid/kfc87e116152063fc3d"
		);
	},
	downFn(url) {
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url: url,
				success(res1) {
					if (res1.statusCode === 200) {
						uni.saveVideoToPhotosAlbum({
							filePath: res1.tempFilePath,
							success(res2) {
								resolve();
							},
							fail(res2) {
								if (res2.errMsg === "saveVideoToPhotosAlbum:fail cancel") {
									// 取消下载
									return;
								}
								reject(res2.errMsg);
							}
						})
					} else {
						reject(res1)
					}
				},
				fail(e) {
					reject(e);
					console.log(11110, res1);
				}
			})
		})
	},
	ajax: function(data) {
		let that = this;
		return new Promise((resolve, reject) => {

			uni.request({
				url: that.config.url + data.url,
				method: data.type || "post",
				header: {
					Authorization: storage.getUser().token, //接口权限验证，和后端约定配合判定      
					...(data.header || {})
				},
				...(data.other || {}),
				data: data.data,
				timeout: 1800000, // 设置超时时间为5秒
				dataType: "json",
				success: function(res) {
					if (code_arr.includes(res.data.code)) {
						uni.navigateTo({
							url: '/pages/login/login'
						})
						uni.showToast({
							title: "未登录",
							icon: 'error',
							duration: 2000
						})
					} else if (res?.data?.code === 0) {
						resolve(res.data);
					} else if (router_arr.includes(data.url) && data.statusCode == 200) {
						resolve(res.data);
					} else {
						uni.hideLoading();
						uni.showToast({
							icon: "none",
							title: "错误：" + (res.data?.message || ""),
							duration: 2000,
							// mask: true, // 否显示透明蒙层
						});
						console.log(res, that.config.url + data.url)
						reject(res)
					}
				},
				fail: function(err) {
					console.log("请求错误", data.url, err, that.config.url);
					reject(err)
				},
			});
		});

	},
}


export default obj;